package com.example.resturant.controller;

import com.example.resturant.dto.SubmitOrderRequestDTO;
import com.example.resturant.model.Comment;
import com.example.resturant.service.OrderService;
import com.example.resturant.vo.ResultVO;
import com.example.resturant.vo.UserVO;
import lombok.var;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RequestMapping("/order")
@Controller
public class OrderController {

    @Resource
    private OrderService orderService;

    @GetMapping
    public String list(Model model, @PageableDefault Pageable page, HttpSession httpSession) {
        Boolean logined = (Boolean) httpSession.getAttribute("logined");
        if (BooleanUtils.isNotTrue(logined)) {
            return "redirect:/index";
        }
        UserVO userVO = (UserVO) httpSession.getAttribute("user");
        if (userVO == null) {
            return "redirect:/index";
        }
        var orders = orderService.listOrders(userVO.getId(), page);
        model.addAttribute("orders", orders);
        return "order";
    }

    @PostMapping("/submit")
    @ResponseBody
    public ResultVO submit(@RequestBody SubmitOrderRequestDTO request, HttpSession httpSession) {
        ResultVO vo = new ResultVO();
        vo.setCode(-1);
        Boolean logined = (Boolean) httpSession.getAttribute("logined");
        if (BooleanUtils.isNotTrue(logined)) {
            vo.setMessage("未登录或登录失效，请登录");
            return vo;
        }
        UserVO userVO = (UserVO) httpSession.getAttribute("user");
        if (userVO == null) {
            vo.setMessage("未登录或登录失效，请登录");
            return vo;
        }
        orderService.submit(userVO.getId(), request);
        vo.setCode(0);
        return vo;
    }

    @PostMapping("/comment")
    @ResponseBody
    public ResultVO comment(@RequestBody Comment request, HttpSession httpSession) {
        ResultVO vo = new ResultVO();
        vo.setCode(-1);
        Boolean logined = (Boolean) httpSession.getAttribute("logined");
        if (BooleanUtils.isNotTrue(logined)) {
            vo.setMessage("未登录或登录失效，请登录");
            return vo;
        }
        UserVO userVO = (UserVO) httpSession.getAttribute("user");
        if (userVO == null) {
            vo.setMessage("未登录或登录失效，请登录");
            return vo;
        }
        orderService.comment(request);
        vo.setCode(0);
        return vo;
    }
}
